from machine import Pin
import time

"""
Rotary Encoder Handler

旋转编码器控制模块，支持：
- 旋转检测（顺时针/逆时针）
- 按键检测（短按/长按）
- 自动消抖处理
"""

class RotaryEncoder:
    def __init__(self, pin_clk, pin_dt, pin_sw):
        self.pin_clk = Pin(pin_clk, Pin.IN, Pin.PULL_UP)
        self.pin_dt = Pin(pin_dt, Pin.IN, Pin.PULL_UP)
        self.pin_sw = Pin(pin_sw, Pin.IN, Pin.PULL_UP)
        
        self.clk_last = self.pin_clk.value()
        self.press_time = 0
        self.last_button_time = 0
        
    def read_rotation(self):
        clk_val = self.pin_clk.value()
        if clk_val != self.clk_last:
            if self.pin_dt.value() == clk_val:
                result = 1
            else:
                result = -1
            self.clk_last = clk_val
            return result
        return 0
    
    def check_button(self):
        # 返回值: 0(未按下), 1(短按), 2(长按)
        current_time = time.ticks_ms()
        if self.pin_sw.value() == 0:  # 按下
            if self.press_time == 0:  # 开始按下
                self.press_time = current_time
            elif current_time - self.press_time > 1000:  # 长按超过1秒
                self.press_time = 0
                self.last_button_time = current_time
                return 2
        elif self.press_time > 0:  # 释放按键
            if current_time - self.press_time > 50:  # 消抖
                if current_time - self.press_time < 1000:  # 短按
                    self.press_time = 0
                    self.last_button_time = current_time
                    return 1
            self.press_time = 0
        return 0 